<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
          <el-form-item label="项目编号" prop="projectNum">
            <el-select  :disabled="isEditMode"
                v-model="dataForm.projectNum"
                placeholder="请选择项目编号"
                class="label_len">
              <el-option
                  v-for="item in projectList"
                  :key="item.prProjectNumber"
                  :label="item.prProjectNumber + ' ' + item.prProjectName"
                  :value="item.prProjectNumber">
              </el-option>
            </el-select>
          </el-form-item>
    <el-form-item label="检查日期" prop="checkDate">
      <el-date-picker
        v-model="dataForm.checkDate"
        type="date"  @change="handleDateChange"
        placeholder="选择检查日期">
      </el-date-picker>
    </el-form-item>
    <el-table :data="tableData" border>
      <el-table-column prop="name" label="资料名称" width="75"></el-table-column>
      <el-table-column prop="content" label="检查内容"></el-table-column>
      <el-table-column prop="method" label="检查方法">
        <template slot-scope="{ row, $index }">
          <span>
            <span v-if="$index === 0">
              制造商规定的产品规格的设计信息与提供的产品执行标准符合 
              <el-input
                v-model="dataForm.checkerMethod"
                placeholder="请输入标准号"
                clearable
                style="width: 130px; display: inline-block;"
              ></el-input>
              相应项目进行一致性检查。
            </span>
            <span v-else>
              制造商规定的产品规格的设计信息与提供的产品技术规范一致。
            </span>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="检查结果" width="120">
        <template slot-scope="scope">
          <el-radio-group v-model="scope.row.result" @change="updateConsistency(scope.row)">
            <el-radio label="一致">一致</el-radio>
            <el-radio label="不一致">不一致</el-radio>
            <el-radio label="不适用">不适用</el-radio>
          </el-radio-group>
        </template>
      </el-table-column>
      <el-table-column label="一致性判定" width="120">
          <template slot-scope="scope">
            <span>{{ getConsistency(scope.row.result) }}</span>
          </template>
        </el-table-column>
    </el-table>
    <el-table-column >
      注：1. 内容为选项的，在相应选项前划√；<br />
          2. 一致性判定合格为“+”，不合格为“-”。
    </el-table-column>
 

    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        tableData: [
        {
          name: '产品执行标准',
          content: '制造商规定的产品规格符合设计信息与提供的产品执行标准所指示的产品技术规范一致。',
          method: '',
          result: '一致',
          consistency: ''
        },
        {
          name: '产品使用说明书',
          content: '制造商规定的产品规格的设计信息与提供的产品技术规范一致。',
          method: '针对产品规格的设计信息与说明书相关项目进行了一致性检查。',
          result: '一致',
          consistency: ''
        }
      ],
        visible: false,
        dataForm: {
          id: 0,
          projectNum: '',
          checkDate: null ,
          checkResult: '',
          testName: '',
          recordName: '',
          checkerName: '',
          createId: '',
          checkerMethod: ""
        },
        projectList: [],
        isEditMode: false,
        dataRule: {
          projectNum: [
            { required: true, message: '项目编号不能为空', trigger: 'blur' }
          ],
          checkDate: [
            { required: true, message: '检查日期不能为空', trigger: 'blur' }
          ],
          checkResult: [
            { required: true, message: '检查结果与一致性判定不能为空', trigger: 'blur' }
          ],
          testName: [
            { required: true, message: '检测人不能为空', trigger: 'blur' }
          ],
          recordName: [
            { required: true, message: '记录人不能为空', trigger: 'blur' }
          ],
          checkerName: [
            { required: true, message: '校核人不能为空', trigger: 'blur' }
          ],
          createId: [
            { required: true, message: '创建人id不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    watch: {
    standardInput(newVal) {
      this.tableData.forEach(item => {
        item.method = `制造商规定的产品规格的设计信息与提供的产品执行标准符合${newVal}相关项进行了一致性检查。`;
      });
    }
  },
    mounted (){
    this.getprojectList()
  },
    methods: {
      //获取项目列表
      getprojectList() {
        this.$http({
          url: this.$http.adornUrl(`/reportapproval/product/getProjectNumber`),
          method: 'post',
          data: this.$http.adornData({
          })
        }).then((data) => {
          if (data && data.code === 0) {
            console.log(data.productList)
            this.projectList = data.productList
          } else {
            this.$message.error(data.msg)
          }
        })
      },
       handleDateChange(value) {
        if (value) {
          // 将选择的日期转换为 UTC 字符串
          const date = new Date(value);
          const utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()));
          this.dataForm.checkDate = utcDate.toISOString();
        }
      },
      updateConsistency(row) {
        if (row.result === '一致') {
          row.consistency = '+';
        } else if (row.result === '不一致') {
          row.consistency = '-';
        } else {
          row.consistency = '/'; // 不适用
        }
      },
      getConsistency(result) {
        if (result === '一致') {
          return '+';
        } else if (result === '不一致') {
          return '-';
        } else {
          return '/'; // 不适用
        }
      },
      init (id) {
         this.isEditMode = false;
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/reportapproval/consistencycheck/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then((data) => {
              if (data && data.code === 0) {
                this.isEditMode =true;
                this.dataForm.projectNum = data.consistencyCheck.projectNum
                this.dataForm.checkDate = data.consistencyCheck.checkDate
                this.dataForm.checkerMethod=data.consistencyCheck.checkerMethod
                // 解析 checkResult
                const checkResultArray = JSON.parse(data.consistencyCheck.checkResult);
                
                this.tableData = this.tableData.map((item, index) => {
                // 根据索引更新 result 和 consistency
                if (checkResultArray[index]) {
                  return {
                    ...item,  // 保持前两列的内容
                    result: checkResultArray[index].result,  // 更新 result
                    consistency: checkResultArray[index].consistency  // 更新 consistency
                  };
                }
                return item; // 如果没有新的检查结果，返回原本的 item
              });

                this.dataForm.testName = data.consistencyCheck.testName
                this.dataForm.recordName = data.consistencyCheck.recordName
                this.dataForm.checkerName = data.consistencyCheck.checkerName
                this.dataForm.createId = data.consistencyCheck.createId
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
         // 收集检查结果和一致性判断
        const checkResultData = this.tableData.map((row, index) => ({
          row: index + 1, // 行数从 1 开始
          result: row.result,
          consistency: row.consistency
        }));

        // 将收集到的信息转为 JSON 字符串
        this.dataForm.checkResult = JSON.stringify(checkResultData);

        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/reportapproval/consistencycheck/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'projectNum': this.dataForm.projectNum,
                'checkDate': new Date(this.dataForm.checkDate).toISOString().split('T')[0],
                'checkResult': this.dataForm.checkResult,
                'testName': this.dataForm.testName,
                'recordName': this.dataForm.recordName,
                'checkerName': this.dataForm.checkerName,
                'createId': this.dataForm.createId,
                'checkerMethod': this.dataForm.checkerMethod
              })
            }).then((data) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      }
    }
  }
</script>
